package dx.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;
/**
 * BASE64 转换
 * create by duanx 2021/4/25
 *@description：
 *@classname: Base64Util
 *@author: duanx
 *@date: 2021/4/25 11:10
 **/


public class Base64Util extends BaseUtil {

    /**
     * 将文件流转成base64 字符串
     *
     * @param inputStream IO输入流
     * @return BASE64串
     */
    public static String encodeBase64File(InputStream inputStream){
        logger.debug("文件流转成base64字符串");
        byte[] buffer;
        String pdfBase64Str = null;
        try {
            buffer = new byte[inputStream.available()];
            inputStream.read(buffer);
            pdfBase64Str = new BASE64Encoder().encode(buffer);
            pdfBase64Str = pdfBase64Str.replace("\n", "").replace("\t", "").replace("\r", "");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return pdfBase64Str;
    }

    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code BASE64串
     * @param targetPath 路径
     * @throws Exception 转换失败
     */
    public static void decoderBase64File(String base64Code, String targetPath) throws Exception {
        logger.debug("将base64字符解码保存文件："+targetPath);
        FileOutputStream out = null;
        try {
            byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
            out = new FileOutputStream(targetPath);
            out.write(buffer);
        } finally {
            if(out != null) {
                out.close();
            }
        }

    }

    /**
     * 将base64字符保存文本文件
     *
     * @param base64Code BASE64串
     * @param targetPath 路径
     * @throws Exception 转换失败
     */
    public static void toFile(String base64Code, String targetPath) throws Exception {
        byte[] buffer = base64Code.getBytes();
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }
}
